package com.fc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fc.context.BaseContext;
import com.fc.dto.pageQuery.AttendancePageQueryDTO;
import com.fc.entity.Attendance;
import com.fc.enums.ClockType;
import com.fc.exception.AttendanceException;
import com.fc.mapper.AttendanceMapper;
import com.fc.result.PageResult;
import com.fc.service.IAttendanceService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;


@Service
public class AttendanceServiceImpl extends ServiceImpl<AttendanceMapper, Attendance> implements IAttendanceService {

    @Override
    public void punchIn(String location,String vehiclePlate) {
        QueryWrapper<Attendance> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("driver_id", BaseContext.getCurrentId())
                .eq("clock_type", ClockType.WORK.getCode())
                .eq("clock_date", LocalDate.now());
        List<Attendance> workAttendance = list(queryWrapper);
        if (!workAttendance.isEmpty()) {
            throw new AttendanceException("已完成打卡");
        }
        save(get(location, ClockType.WORK.getCode(),vehiclePlate));
    }

    @Override
    public void punchOut(String location,String vehiclePlate) {
        // 检查是否已存在上午打卡记录
        QueryWrapper<Attendance> workQueryWrapper = new QueryWrapper<>();
        workQueryWrapper.eq("driver_id", BaseContext.getCurrentId())
                .eq("clock_type", ClockType.WORK.getCode())
                .eq("clock_date", LocalDate.now());
        List<Attendance> workAttendance = list(workQueryWrapper);
        if (workAttendance.isEmpty()) {
            throw new AttendanceException("请先进行上午打卡");
        }

        QueryWrapper<Attendance> breakQueryWrapper = new QueryWrapper<>();
        breakQueryWrapper.eq("driver_id", BaseContext.getCurrentId())
                .eq("clock_type", ClockType.BREAK.getCode())
                .eq("clock_date", LocalDate.now());
        List<Attendance> breakAttendance = list(breakQueryWrapper);
        if (!breakAttendance.isEmpty()) {
            throw new AttendanceException("已完成打卡");
        }
        // 保存下午打卡记录
        save(get(location, ClockType.BREAK.getCode(),vehiclePlate));
    }

    @Override
    public PageResult listByDriver(AttendancePageQueryDTO attendancePageQueryDTO) {
        // 使用当前用户的 driverId
        attendancePageQueryDTO.setDriverId(BaseContext.getCurrentId());
        return queryAttendancePage(attendancePageQueryDTO);
    }

    @Override
    public PageResult listPage(AttendancePageQueryDTO attendancePageQueryDTO) {
        // 直接使用传入的 DTO 参数
        return queryAttendancePage(attendancePageQueryDTO);
    }


    /**
     * 提取公共查询逻辑
     */
    private PageResult queryAttendancePage(AttendancePageQueryDTO attendancePageQueryDTO) {
        // 创建分页对象
        Page<Attendance> page = new Page<>(attendancePageQueryDTO.getPageNum(), attendancePageQueryDTO.getPageSize());
        // 构建查询条件
        Page<Attendance> attendancePage = lambdaQuery()
                .eq(attendancePageQueryDTO.getDriverId() != null, Attendance::getDriverId, attendancePageQueryDTO.getDriverId())
                .eq(attendancePageQueryDTO.getClockType() != null, Attendance::getClockType, attendancePageQueryDTO.getClockType())
                .between(attendancePageQueryDTO.getStartTime()!=null && attendancePageQueryDTO.getEndTime()!=null,
                        Attendance::getClockTime, attendancePageQueryDTO.getStartTime(), attendancePageQueryDTO.getEndTime())
                .orderByDesc(Attendance::getClockTime)
                .page(page);
        // 返回分页结果
        return new PageResult(attendancePage.getTotal(), attendancePage.getRecords());
    }

    private Attendance get(String location, Integer clockType,String vehiclePlate) {
        return Attendance.builder()
                .driverId(BaseContext.getCurrentId())
                .clockTime(LocalDateTime.now())
                .clockDate(LocalDate.now())
                .location(location)
                .vehiclePlate(vehiclePlate)
                .clockType(clockType)
                .build();
    }

}
